import React, {Component} from 'react';
import { observable, action, autorun, computed, toJS } from 'mobx';
import {Tools, Bubble } from 'weaver-mobile';
import { ListViewPage, SearchAdvanced, RouteLayout } from 'weaver-mobile-page';
import showTemplates from '../../components/outSign/record/ListTemplate';
import subTemplates from '../../components/resource/showTemplates/index';
import BaseStore from '../BaseStore';
import MapUtil from '../../util/mapUtil';
import {getLocation} from '../../util/jemUtil';
import * as api from '../../apis/sign';
import * as resourceAPI from '../../apis/resource';
import moment from 'moment';
import cloneDeep from 'lodash/cloneDeep';

const getLabel = Tools.getLabel;

const conditionUrl = '/api/hrm/kq/attendanceButton/getOutButtonCondition';
const subConditionUrl = '/api/public/browser/condition/1'

class OutSignRecordStore extends BaseStore{
    //#region 初始化
    @observable _outSignStoreV2;
    @computed get outSignStoreV2(){return this._outSignStoreV2}
    set outSignStoreV2(v){this._outSignStoreV2 = v}

    monitorTabPage = () => {
        const {initialPage} = this.outSignStoreV2 || {};
        if(initialPage == 1){
            this.setActiveTab(0);
        }
	}
    monitor = autorun(this.monitorTabPage);

    @computed get baseInfo(){return this.outSignStoreV2.baseInfo}
    resourceId;
    @observable advanceSearchPageStore = new SearchAdvanced.Store({route: '/outSignV2', id: 'advanceSearch'});//打卡记录高级搜索
    @observable resourceRecordAdvanceSearchPageStore = new SearchAdvanced.Store({route: '/outSignV2/record', id: 'advanceSearch'});//下属考勤打卡记录详情高级搜索
    //#endregion

    //#region 外勤打卡记录tab配置
    @observable _recordInitialPage = 0;
    @computed get recordInitialPage(){return this._recordInitialPage}
    set recordInitialPage(v){this._recordInitialPage = v}
    
    @computed get tabConfig(){
        return {
            tabs: [
                {title: getLabel('503732','我的外勤')},
                {title: getLabel('504541','下属外勤')}
            ],
            tabProps: {
                initialPage: this.recordInitialPage,
                page: this.recordInitialPage,
                onTabClick: (tab, index) => {
                    this.setActiveTab(index);
                }
            }
        }
    }

    @action setActiveTab = async index => {
        this.recordInitialPage = index;
        if(index == 0){
            this.viewType = 0;
            this.queryOutSignRecord();
        }else{
            this.initSubordinatePage();
        }
    }
    //#endregion

    //#region 获取打卡记录
    currentPage = 1; 
    pageSize = 20;

    @observable listViewStore = new ListViewPage.Store();
    @observable _listDatas = [];
    @computed get listDatas(){return toJS(this._listDatas)}
    set listDatas(v){this._listDatas = v}
    @observable count = 0;

    get advanceSearchStore(){
        if(this.resourceId)
            return this.resourceRecordAdvanceSearchPageStore;
        return this.advanceSearchPageStore;
    }

    get queryParams (){
        const {form: {formParams}} = this.advanceSearchStore;
        const params = {
            ...formParams,
            pageIndex: this.currentPage,
            pageSize: this.pageSize
        }
        this.resourceId != null && Object.assign(params, {resourceId: this.resourceId});
        return params;
    }

    @action cleanData = () => {
        this.listViewStore = new ListViewPage.Store();
        this.currentPage = 1;
        this.listDatas = [];
    }

    @action resetCondition = () => {
        const {form} = this.advanceSearchStore;
        form.resetFields();
    }

    @action queryOutSignRecord = async resourceId => {
        this.resourceId = resourceId;
        const form = await this.advanceSearchStore.getData({url: conditionUrl});
        if(form.isInit){
            this.resetCondition();
            this.setCurrentPage(1);
        }
    }

    @action setCurrentPage = idx => {
        if(idx == null)
            this.currentPage++;
        else if(idx === this.currentPage && this.currentPage != 1){
            this.listViewStore.setState({hasMore: false, loading: false});
            return;
        } else{
            this.cleanData();
        }
        this.queryData();
    }

    @action queryData = async () => {
        this.listViewStore.setState({
            loading: true
        });
        const data = await api.getOutSearchList({data: JSON.stringify({...this.queryParams, order: 1})});
        if(data.status == '1'){
            this.setListData(data);
        }else{
            Bubble.error(data.message);
        }
    }

    @action setListData = data => {
        const { count } = data;
        const datas = data.datas.map((d, index) => {
            return {
                ...d,
                imgList: d.attachment.map(v => `/weaver/weaver.file.FileDownload?fileid=${v}`)
            }
        });
        const { template } = showTemplates;
        this.count = count;
        this.listDatas = [...this.listDatas, ...datas];
        
        const dataSource = this.listViewStore.dataSource.cloneWithRows(this.listDatas);
        this.listViewStore.setState({
            nameKey: this.nameKey,
            rowKey: this.rowKey,
            data: this.listDatas,
            template: { template },
            dataSource,
            hasMore: datas.length > 0 && this.count >= this.pageSize,
            loading: false,
            isTable: false,
            getData: () => {}
        });
    }
    //#endregion
    
    //#region 下属人员列表
    @observable subAdvanceSearchPageStore = new SearchAdvanced.Store({route: '/outSignV2', id: 'subAdvanceSearch'});//下属考勤人员高级搜索
    @observable resourceRecordLayout = new RouteLayout.Store({ route: '/outSignV2', id: 'record' });//下属考勤打卡记录详情

    subCurrentPage = 1;
    @observable subListViewStore = new ListViewPage.Store();

    @observable _subListDatas = [];
    @computed get subListDatas(){return toJS(this._subListDatas)}
    set subListDatas(v){this._subListDatas = v}

    @observable _subCount = 0;
    @computed get subCount(){return toJS(this._subCount)}
    set subCount(v){this._subCount = v}

    @observable _showPop = false;
    @computed get showPop(){return toJS(this._showPop)}
    set showPop(v){this._showPop = v}

    @observable _alllevel = true;
    @computed get alllevel(){return toJS(this._alllevel)}
    set alllevel(v){this._alllevel = v}

    get subQueryParams (){
        const {form: {formParams}} = this.subAdvanceSearchPageStore;
        const params = {
            ...formParams,
            cmd: 'search',
            mobileResourceId: this.baseInfo.userid
        }
        Object.assign(params, {
            min: (this.subCurrentPage - 1) * this.pageSize + 1,
            max: this.subCurrentPage * this.pageSize,
            alllevel: this.alllevel ? 1 : 0
        })
        return params;
    }

    @action cleanSubData = () => {
        this.subListViewStore = new ListViewPage.Store();
        this.subCurrentPage = 1;
        this.subListDatas = [];
    }

    @action resetSubCondition = () => {
        const {form} = this.subAdvanceSearchPageStore;
        form.resetFields();
    }

    @action initSubordinatePage = async () => {
        const form = await this.subAdvanceSearchPageStore.getData({url: subConditionUrl});
        if(form.isInit){
            this.resetSubCondition();
            this.setSubCurrentPage(1);
        }
    }

    @action setSubCurrentPage = idx => {
        if(idx == null)
            this.subCurrentPage++;
        else if(idx === this.subCurrentPage && this.subCurrentPage != 1){
            this.listViewStore.setState({hasMore: false, loading: false});
            return;
        } else{
            this.cleanSubData();
        }
        this.querySubData();
    }

    @action querySubData = async () => {
        this.subListViewStore.setState({
            loading: true
        });
        const data = await resourceAPI.queryData(this.subQueryParams);
        const {datas} = data;
        Array.isArray(datas) && this.setSubListData(data);
    }

    @action setSubListData = data => {
        const {
            count,
            datas
        } = data;
        const {
            template
        } = subTemplates;
        this.subCount = count;
        this.subListDatas = [...this.subListDatas, ...datas];

        const dataSource = this.subListViewStore.dataSource.cloneWithRows(this.subListDatas);
        this.subListViewStore.setState({
            nameKey: this.nameKey,
            rowKey: this.rowKey,
            data: this.subListDatas,
            template: {
                template
            },
            dataSource,
            hasMore: datas.length > 0 && this.subCount >= this.pageSize,
            loading: false,
            isTable: false,
            getData: () => {}
        });
    }

    @action onPopoverSelectHandle = () => {
        this.alllevel = !this.alllevel;
        this.setSubCurrentPage(1);
        this.showPop = false;
    }

    @action doQuickSearch = () => {
        this.cleanSubData();
        this.setSubCurrentPage(1);
    }

    @action onQuickSearchChangeHandle = v => {
        const {
            form
        } = this.subAdvanceSearchPageStore;
        form.updateField('lastname', v.toString());
    }

    @action onClearSearchCondition = () => {
        this.onQuickSearchChangeHandle('');
        this.doQuickSearch();
    }
    //#endregion

    //#region 地图相关
    @observable _viewType = 0;//0.list 1.map
    @computed get viewType(){return this._viewType}
    set viewType(v){this._viewType = v}

    @observable mapUtil = new MapUtil();

    @action onMapTypeChangeHandle = async () => {
        this.Toast.loading('loading', 0);
        this.locationInfo = await getLocation(this.mapUtil);
        this.outSignStoreV2.mapUtil.setMapType(this.mapUtil.currentMapType);
        this.Toast.hide();
    }
    //#endregion

    //#region 地图数据
    @observable _searchDate = moment().format('YYYY-MM-DD');
    @computed get searchDate(){return toJS(this._searchDate)}
    set searchDate(v){this._searchDate = v}

    @observable _mapDatas = [];
    @computed get mapDatas(){return toJS(this._mapDatas)}
    set mapDatas(v){this._mapDatas = v}

    init = () => {
        // this.mapStore = new MapPage.Store();
        this.searchDate = moment().format('YYYY-MM-DD');
        const {currentMapType} = this.outSignStoreV2.mapUtil;
        this.mapUtil.setMapType(currentMapType);
    }

    initMap = async callback => {
        // this.mapStore = new MapPage.Store();
        // this.searchDate = moment().format('YYYY-MM-DD');
        const datas = await this.queryMapData();
        callback && callback();
    }

    @action queryMapData = async () => {
        let params = cloneDeep(this.queryParams);
        Object.assign(params, {
            signtypecondition: '2',
            typeselectselect: '6', 
            typeselectfrom: this.searchDate,
            typeselectto: this.searchDate
        });
        delete params.pageIndex;
        delete params.pageSize;
        const data = await api.getOutSearchList({data: JSON.stringify(params)});
        if(data.status == '1'){
            if(data.datas == null || data.datas.length == 0){
                this.mapDatas = [];
                Bubble.warning(getLabel(83553, '暂无数据'));
            }else{
                this.mapDatas = data.datas;
            }
            // callback && callback(data.datas);
        }else{
            Bubble.error(data.message);
        }
    }

    @action onDateChangeHandle = async (date, callback) => {
        this.searchDate = date;
        const datas = await this.queryMapData();
        callback && callback();
    }
    //#endregion
}

export const outSignRecordStore = new OutSignRecordStore(); 